package com.paddyi.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.paddyi.mapper.ResourceMapper;
import com.paddyi.model.Resource;
import com.paddyi.service.IResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

/**
 * 资源 (Resource)
 *
 * @author paddy
 * @since 2019-04-26 04:34:10
 */
@Service
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, Resource> implements IResourceService {

    @Autowired
    ResourceMapper resourceMapper;


    @Override
    public List<Resource> selectResourceTreeByLoginName(List<Long> roleIds) {
        List<Resource> resources = resourceMapper.selectResourceMenusTreeByLoginName(roleIds);
        List<Resource> resourceVos = new ArrayList<>();
        for(Resource resource:resources){
            if(resource.getPid() == 0 ){
                resourceVos.add( resource);
                children(resource,resources);
            }
        }
        resourceVos.sort(Comparator.comparing(Resource::getSeq));

        return resourceVos;
    }

    @Override
    public Set<String> selectResourceButtonByLoginName(List<Long> roleIds) {
        Set<String> perms = new HashSet<>();
        List<Resource> resources = resourceMapper.selectResourceButtonByLoginName(roleIds);
        for(Resource resource : resources){
            perms.add(resource.getUrl().substring(1,resource.getUrl().length()).replace("/",":"));
        }
        return perms;
    }

    @Override
    public List<Resource> findTree() {

        List<Resource> resources = this.list();
        List<Resource> resourceVos = new ArrayList<>();
        for(Resource resource:resources){
            if(resource.getPid() == 0 ){
                resourceVos.add(resource);
                children(resource,resources);
            }
        }
        resourceVos.sort(Comparator.comparing(Resource::getSeq));

        return resourceVos;
    }

    @Override
    public List<Resource> findResourceByRoleId(Long roleId) {
        return resourceMapper.selectResourceByRoleId(roleId);
    }

    private void children (Resource resource,List<Resource> resources){
            List<Resource> childrens = new ArrayList<>();
            for(Resource re:resources){
                if(re.getPid() !=null && resource.getId().longValue() == re.getPid().longValue()){
                    re.setParentName(resource.getName());
                    childrens.add(re);
                    children(re, resources);
                }
            }
            childrens.sort(Comparator.comparing(Resource::getSeq));
            resource.setChildren(childrens);

    }

}
